package com.wenhuitec.android.tang.ui.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.dhkj.web.bean.AddrTree;
import com.dhkj.web.bean.PrintReportModel;
import com.dhkj.web.bean.TangReportTime;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.wenhuitec.android.tang.R;
import com.wenhuitec.android.tang.config.SystemInit;
import com.wenhuitec.android.tang.sysui.model.PickModel;
import com.wenhuitec.android.tang.sysui.view.PickView;
import com.wenhuitec.android.tang.ui.dialog.WithDialog;
import com.wenhuitec.android.tang.util.BytesUtil;
import com.wenhuitec.android.tang.util.PrintUtil;
import com.wenhuitec.android.tang.util.UsbPrinter;

import org.w3c.dom.Text;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class ReportActivity extends AppCompatActivity {
    private Context mContext;
    private PickView addressPv;
    private PickView shopPv;
    private PickView timePv;
    private TextView dateTv;
    private List<AddrTree> addrTreeList;
    private int addr;
    private String timeId;
    private UsbPrinter usbPrinter;
    Calendar calendar = Calendar.getInstance(Locale.CHINA);//获取日期格式器对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report);
        mContext = this;
        addressPv = findViewById(R.id.addressPv);
        shopPv = findViewById(R.id.shopPv);
        timePv = findViewById(R.id.timePv);
        dateTv = findViewById(R.id.dateTv);
        addrTreeList = SystemInit.getInstance(mContext).getAddrTreeList();
        usbPrinter = UsbPrinter.getInstance(this);
        findViewById(R.id.datePickerBut).setOnClickListener(view -> {
            //生成一个DatePickerDialog对象，并显示。显示的DatePickerDialog控件可以选择年月日，并设置
            DatePickerDialog datePickerDialog = new DatePickerDialog(ReportActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    //修改日历控件的年，月，日
                    //这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
                    calendar.set(Calendar.YEAR, year);
                    calendar.set(Calendar.MONTH, month);
                    calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateTimeShow();
                }
            }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.show();
            updateTimeShow(); //将页面TextView的显示更新为最新时间

        });
        initAddress();
        initReportTime();
        updateTimeShow();
        SharedPreferences sharedPreferences =
                mContext.getSharedPreferences("systemI", Context.MODE_PRIVATE); //私有数据
        String user = sharedPreferences.getString("user", "");
        findViewById(R.id.printReportBut).setOnClickListener(view -> {
            System.out.println("开始打印报表");
            if (addr == 0 || timeId == null || "".equals(timeId)) {
                Toast.makeText(mContext, "请选择相应参数再查询", Toast.LENGTH_LONG).show();
                return;

            }

            String date = dateTv.getText().toString();
            RequestUtils.getReport(mContext, addr, timeId, date, user,
                    new MyObserverRes<PrintReportModel>(mContext) {
                        @Override
                        public void onSuccess(PrintReportModel result) {
                            System.out.println(result.toString());
                            PrintUtil.setPrintDevice(SystemInit.getInstance(mContext).getPrintDeviceType());
                            byte[] printByte = BytesUtil.printReport(result, user);
                            try {
                                if (printByte != null) {
                                    usbPrinter.write(printByte);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Throwable e, String errorMsg) {

                        }
                    });
        });
        startActivity(new Intent(mContext, WithDialog.class));
        findViewById(R.id.jiesuanBut).setOnClickListener(view -> {
            startActivity(new Intent(mContext, WithDialog.class));
        });
    }

    private void initReportTime() {
        timePv.setTitle("时间：");
        List<PickModel> pickModelList = new ArrayList<>();
        for (TangReportTime goo : SystemInit.getInstance(mContext).getTangReportTimeList()) {
            pickModelList.add(new PickModel(goo.getId(), goo.getName().trim()));
        }
        timePv.setRv(pickModelList);
        timePv.setOnClick((pickModel, position) -> {
            System.out.println(pickModel.getId());
            timeId = pickModel.getId();
        });
    }

    private void updateTimeShow() { //将页面TextView的显示更新为最新时间
        String time = new SimpleDateFormat("yyy-MM-dd").format(calendar.getTime());
        dateTv.setText(time);
    }

    private void initAddress() {
        addressPv.setTitle("地点：");
        List<PickModel> pickModelList = new ArrayList<>();
        for (AddrTree goo : addrTreeList) {
            pickModelList.add(new PickModel(goo.getId(), goo.getAddrName().trim()));
        }
        addressPv.setRv(pickModelList);
        addressPv.setOnClick((pickModel, position) -> {
            initShop(pickModel.getId());
        });
    }

    private void initShop(String id) {
        shopPv.setTitle("商铺：");
        AddrTree addrTree = addrTreeList.stream().filter(u -> u.getId().equals(id)).findFirst().orElse(new AddrTree());
        List<PickModel> pickModelList = new ArrayList<>();
        if (addrTree != null) {
            for (AddrTree goo : addrTree.getChildren()) {
                pickModelList.add(new PickModel(goo.getId(), goo.getAddrName().trim()));
            }
        }
        shopPv.setRv(pickModelList);
        shopPv.setOnClick((pickModel, position) -> {
            try {
                addr = Integer.parseInt(pickModel.getId());
            } catch (Exception e) {
                addr = 0;
            }
        });
    }

}
